package com.extweb4j.web.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;

import cn.dreampie.mail.Mailer;

import com.extweb4j.core.anno.AuthAnno;
import com.extweb4j.core.anno.Log;
import com.extweb4j.core.controller.ExtController;
import com.extweb4j.core.enums.MsgStatus;
import com.extweb4j.core.enums.RowStatus;
import com.extweb4j.core.kit.ExtKit;
import com.extweb4j.core.kit.LoginKit;
import com.extweb4j.core.kit.SMSKit;
import com.extweb4j.core.model.ExtLog;
import com.extweb4j.core.model.ExtMsg;
import com.extweb4j.core.model.ExtMsgUser;
import com.extweb4j.core.model.ExtUser;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 系统消息控制器
 * 
 * @author Administrator
 *
 */
public class MsgController extends ExtController {
	
	/**
	 * 列表
	 */
	@AuthAnno
	public void list() {
		int page = getParaToInt("page");
		int limit = getParaToInt("limit");
		String keywords = getPara("keywords");
		Page<ExtMsg> pageData = ExtMsg.dao.paginateByKeywaord(page, limit,
				keywords, getUid());
		// 将uid转化为username
		for (ExtMsg msg : pageData.getList()) {
			msg.set("uid", ExtUser.dao.findUserNameById(msg.getStr("uid")));
		}
		renderJson(pageData);
	}
	/*
	 * 新增消息
	 */
	@Log("新建消息")
	@AuthAnno
	@Before(Tx.class)
	public void add() {
		ExtMsg msg = getExtModel(ExtMsg.class);
		String tpl_id = getPara("tpl_id");
    	String place = getPara("place_name");
		String time = getPara("excute_time");
		String content = getPara("msg_content");
		msg.set("id", ExtKit.UUID());
		msg.set("uid", getUid());
		msg.set("create_time", new Timestamp(new Date().getTime()));
		msg.set("msg_content", SMSKit.getContent(tpl_id, place, time,content));
		// 绑定消息和用户
		if (msg.save() && bindMsgUser(getPara("_userIds").split(","), msg.getStr("id"))) {
			success();
		} else {
			msg.deleteById(msg.getStr("id"));
			error("保存失败");
		}
	}
	/**
	 * 编辑
	 */
	@Log("编辑信息")
	@AuthAnno
	@Before(Tx.class)
	public void edit() {
    	ExtMsg msg = getExtModel(ExtMsg.class);
		// 删除已有的消息部门关系
		ExtMsgUser.dao.deleteByAttr("msg_id", msg.getStr("id"));
		// 绑定消息和用户
		if (msg.update()&& bindMsgUser(getPara("_userIds").split(","), msg.getStr("id"))) {
			success();
		} else {
			error("编辑失败");
		}
	}
	/**
	 * 绑定msg和user表关系
	 * 
	 * @param deptIds
	 * @param msg_id
	 */
	public boolean bindMsgUser(String[] userIds, String msg_id) {
		boolean flag = false;
		if (ArrayUtils.isEmpty(userIds)) {
			throw new RuntimeException("无效的用户");
		}
		for (String userId : userIds) {
			ExtMsgUser emd = new ExtMsgUser();
			emd.set("id", ExtKit.UUID());
			emd.set("msg_id", msg_id);
			emd.set("user_id", userId);
			emd.set("status", MsgStatus.待处理.getState());
			if (emd.save()) {
				flag = true;
			}
		}	
		return flag;
	}
	/**
	 * 逻辑删除
	 */
	@Log("删除信息")
	@AuthAnno
	@Before(Tx.class)
	public void delete() {
		ExtMsgUser msg = ExtMsgUser.dao.findFirstByMsgId(getPara("id"),getUid());
		if (msg == null) {
			throw new RuntimeException("要删除的信息不存在");
		}
		msg.set("status", RowStatus.删除.getState());
		msg.update();
		success("删除消息成功");
	}
	/**
	 * 批量删除消息
	 */
	@Log("批量删除信息")
	@AuthAnno
	@Before(Tx.class)
	public void deleteBatch(){
		String[] ids= getParaValues("ids");
		if(ArrayUtils.isEmpty(ids)){
			throw new RuntimeException("请选择要删除的数据");
		}
		for(String id : ids){
			ExtMsgUser msg = ExtMsgUser.dao.findFirstByMsgId(id,getUid());
			msg.set("status", RowStatus.删除.getState());
			msg.update();
		}
		success(ids.length+"条记录已删除");
	}
	/**
	 * 批量确认消息
	 */
	@Log("批量确认信息")
	@Before(Tx.class)
	public void confirmBatch(){
		String[] ids= getParaValues("ids");
		if(ArrayUtils.isEmpty(ids)){
			throw new RuntimeException("请选择要确认的消息");
		}
		for(String id : ids){
			confirm(id);
		}
		success(ids.length+"条消息已确认");
	}
	/**
	 * 确认处理消息
	 */
	public void confirm(String id) {
		ExtMsgUser msg = ExtMsgUser.dao.findFirstByMsgId(id,getUid());
		msg.set("status", MsgStatus.已处理.getState());
		msg.set("action_time", new Timestamp(new Date().getTime()));
		msg.update();
	}
	/**
	 * 发送消息
	 */
	@Log("发送信息")
	@AuthAnno
	@Before(Tx.class)
	public void sendMessage() {
		ExtMsg msg = ExtMsg.dao.findById(getPara("id"));
		List<ExtUser> user = ExtMsgUser.dao.findUserByMsgId(getPara("id"));
		Map<String,List<String>> map = SMSKit.getPhonesAndEmails(user);
		//邮箱，电话数组
		List<String> phones = map.get("phones");
		String[] emails = ExtKit.PraseListToStringArray(map.get("emails"));
		//发送邮件短信
		Mailer.sendText(msg.getStr("msg_title"),msg.getStr("msg_content"),emails);
		String result = SMSKit.batchSend(phones, msg.getStr("msg_content"));
		//记录日志
		new ExtLog()
    	.set("id", ExtKit.UUID())
    	.set("user_name", LoginKit.getSessionUser(getRequest()).getStr("user_name"))
    	.set("action_text", "发送邮件")
    	.set("method", "POST")
    	.set("log_url", "/msg/sendMessage")
    	.set("log_params","邮箱:"+JsonKit.toJson(emails)+"手机号码:"+JsonKit.toJson(phones))
    	.set("create_time", new Timestamp(new Date().getTime()))
    	.save();
		if(result.equals(SMSKit.value)){
			success();
		}else{
			error(result);
		}
	}
	
	public String getUid(){
		ExtUser user = LoginKit.getSessionUser(getRequest());
		return user.getId();
	}
	/**
	 * 根据Id获取一条记录，编辑
	 */
	public void get() {
		ExtMsg msg = ExtMsg.dao.findById(getPara("id"));
		List<ExtUser> user = ExtMsgUser.dao.findUserByMsgId(msg.getStr("id"));
		List<String> deptIds = new ArrayList<String>();
		for (ExtUser ext : user) {
			deptIds.add(ext.getStr("dept_id"));
		}
		msg.put("dept_id", deptIds);
		renderJson(new Record().set("success", true).set("data", msg));
	}
	/**
	 * 获取我的消息
	 */
	public void getmemsg() {
		int all = 0;
		List<ExtMsgUser> mu = ExtMsgUser.dao.findByAttr("user_id", getUid());
		for (ExtMsgUser msg : mu) {
			if (msg.getStr("status").equals(MsgStatus.待处理.getState())) {
				all++;
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		// 获取所有待处理信息
		map.put("all", all);
		renderJson(map);
	}
}
